package cn.tangsihai.shoptrolley.controller;

import cn.tangsihai.basic.exception.MyException;
import cn.tangsihai.basic.util.AjaxResult;
import cn.tangsihai.shoptrolley.domain.ShopCart;
import cn.tangsihai.shoptrolley.service.IShopCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/shopCart")
public class AddCartController {
    @Autowired
    private IShopCartService shopCartService;

    /**
     * 加入购物车
     * @param petId
     * @return
     */
    @RequestMapping("/addCart/{id}")
    public AjaxResult addCart(@PathVariable("id") Long petId){
        try {
            shopCartService.addCart(petId);
            return AjaxResult.me();
        }catch (MyException e) {
            return AjaxResult.me().setMsg(e.getMessage());
        }
        catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("系统异常");
        }
    }

    /**
     * 加载购物车
     * @param petId
     * @return
     */
    @PostMapping("/carts")
    public AjaxResult carts(){
        try {
            List<ShopCart> cartList = shopCartService.findAllByLogininfoId();
            return AjaxResult.me().setResultObj(cartList);
        }catch (MyException e) {
            return AjaxResult.me().setMsg(e.getMessage());
        }
        catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("系统异常");
        }
    }

    /**
     * 删除购物车中的数据
     * @param petId
     * @return
     */
    @DeleteMapping("/remove/{id}")
    public AjaxResult remove(@PathVariable("id") Long id){
        try {
            shopCartService.remove(id);
            return AjaxResult.me();
        }catch (MyException e) {
            return AjaxResult.me().setMsg(e.getMessage());
        }
        catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("系统异常");
        }
    }

    /**
     * 计算选择数据的总价
     * @param ids
     * @return
     */
    @PostMapping("/getPrices")
    public AjaxResult getPrices(@RequestBody List<Long> ids){
        try {
            BigDecimal prices = shopCartService.getPrices(ids);
            return AjaxResult.me().setResultObj(prices);
        }catch (MyException e) {
            return AjaxResult.me().setMsg(e.getMessage());
        }
        catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("系统异常");
        }
    }
}
